//
//  JKResponse.m
//  app
//
//  Created by huangbenhua on 15-4-10.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "JKResponse.h"

@interface JKResponse()
{
    JKResponseStatus _status;
    NSString* _message;
    NSError* _error;
    NSDictionary* _content;
    
    NSURLRequest * _request;
    
    NSHTTPURLResponse * _response;
}

@end

@implementation JKResponse

-(id)initWithResponse:(id)response req:(id)req
{
    return [self initWithResponse:nil req:req data:response];
}

-(id)initWithResponse:(id)resp req:(id)req data:(id)data
{
    _request = req;
    
    self = [super init];
    if (!self) {
        return self;
    }
    if (!data) {
        _status = JKResponseLocalError;
        return self;
    }
    NSError* err;
    if ([data length]) {
        _content = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
    }else{
        _content = @{};
    }
    //NSLog(@"result of %@ is:\n%@", path, json);
    if (err || !_content) {
        _error = err;
        _status = JKResponseLocalError;
        return self;
    }
    
    _status = [[self numberForKey:@"ret"] integerValue];
    _message = [self stringForKey:@"msg"];
//    _timestamp = [[self numberForKey:@"timestamp"] longValue];
    _response = resp;
    
    id rt = [_content objectForKey:@"result"];
    if (!rt) {
        _content = @{};
    }else if([rt isKindOfClass:NSDictionary.class]){
        _content = rt;
    }else if([rt isKindOfClass:NSArray.class]){
        if ([rt count] < 1) {
            _content = @{};
        }else{
            _content = @{@"result":rt};
        }
    }else{
        _content = @{@"result":rt};
    }
    
    return self;
}

-(id)initWithError:(NSError*)error req:(id)req
{
    _request = req;
    
    self = [super init];
    if (self) {
        _status = JKResponseLocalError;
        _error = error;
    }
    return self;
}
-(NSString*)message
{
    return _message;
}
-(JKResponseStatus)status
{
    return _status;
}

-(NSError *)error
{
    return _error;
}

#pragma mark - 获取服务器时间戳
/*! @brief 获取响应头的时间戳
 *
 * 此方法会获取你的请求获取到响应头上标记的网络时间     但基于不同网络服务器的返回机制可能你的响应头里面标记的网络时间是过时的,所以这个方法使用的时候需要谨慎...
 *
 * @param 无
 * @return long 当前请求中返回的响应头的时间戳
 */
-(long)timestamp{
    NSString * dateStr = [self getResponseHeader:@"Date"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    formatter.dateFormat = @"EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz";
    NSDate * webDate = [formatter dateFromString:dateStr];

    NSString * time1970Str = @"1970/1/1 08:00:00";
    formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
    NSDate * date1970 = [formatter dateFromString:time1970Str];
    
    NSTimeInterval aTimer = [webDate timeIntervalSinceDate:date1970];
    
    return aTimer;
}

-(NSDictionary *)content{
    if (!_content) {
        return @{};
    }
    return _content;
}
-(BOOL)OK
{
    return _status == JKResponseOK || _status == JKResponseTail;
}

-(BOOL)success
{
    return _content && _error == nil;
}

-(BOOL)failure
{
    return _content == nil || _error;
}

-(BOOL)isTail
{
    return _status == JKResponseTail;
}

-(BOOL)hasContent
{
    return _content != nil;
}

-(BOOL)hasMore
{
    return _status == JKResponseOK;
}

-(BOOL)hasError
{
    return _content == nil;
}

-(id)objectForKey:(NSString *)key
{
    return [self objectForKey:key nilValue:nil];
}

-(id)objectForKey:(NSString *)key nilValue:(id)val
{
    if (_content) {
        id val = [_content objectForKey:key];
        if (val) {
            return val;
        }
    }
    return val;
}

-(NSDictionary*)dictForKey:(NSString *)key
{
    if (_content) {
        return [_content dictForKey:key];
    }
    return @{};
}

-(NSArray *)arrayForKey:(NSString *)key
{
    if (_content) {
        return [_content arrayForKey:key];
    }
    return @[];
}

-(NSString *)stringForKey:(NSString *)key nilValue:(NSString *)str
{
    if (_content) {
        return [_content stringForKey:key nilValue:str];
    }
    return str;
}

-(NSString *)stringForKey:(NSString *)key
{
    return [self stringForKey:key nilValue:@""];
}

-(NSNumber *)numberForKey:(NSString *)key
{
    return [self numberForKey:key nilValue:@0];
}

-(NSNumber *)numberForKey:(NSString *)key nilValue:(NSNumber *)num
{
    if (_content) {
        return [_content numberForKey:key nilValue:num];
    }
    return num;
}

- (NSArray *)getCookies
{
    
    NSURL * baseUrl = [self getBaseUrlWithRequest:_request];
    
    if (baseUrl) {
        return [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:baseUrl];
    } else {
        return @[];
    }
}

- (NSURL *)getBaseUrlWithRequest:(NSURLRequest *)request
{
    NSMutableString * baseUrl = [[NSMutableString alloc] init];
    
    [baseUrl appendString:request.URL.scheme];
    [baseUrl appendString:@"://"];
    [baseUrl appendString:request.URL.host];
    
    return [NSURL URLWithString:baseUrl];
}

- (NSHTTPCookie*)getCookie:(NSString*)name
{
    NSArray * cookies = [self getCookies];
    
    for (NSHTTPCookie * subCookie in cookies) {
        if ([[subCookie name] isEqualToString:name]) {
            return subCookie;
        }
    }
    
    return nil;
}

- (NSString *)getResponseHeader:(NSString*)name
{
    if (!_response) {
        return nil;
    }
    
    NSDictionary * dict = [_response allHeaderFields];
    return [dict objectForKey:name];
}

- (void)refreshTheDifferentOfNativeTimeAndWebTime
{
    NSString * dateStr = [self getResponseHeader:@"Date"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    formatter.dateFormat = @"EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz";
    NSDate * networkDate = [formatter dateFromString:dateStr];
    
    NSDate * nativeDate = [NSDate date];
    
    NSTimeInterval aTimer = [nativeDate timeIntervalSinceDate:networkDate];
    
    SNBaseInfoManager * baseInfoManager = [SNBaseInfoManager shareManager];
    [baseInfoManager setBaseInfoObject:[NSString stringWithFormat:@"%f",aTimer] forKey:kDifferenceNativeWithResponseHeader];
}

@end

